import { ApiCall } from "tsrpc";
import * as uuid from 'uuid';
import { ReqJoinSubWorld, ResJoinSubWorld } from "../../shared/protocols/worldServer/PtlJoinSubWorld";
import { UserInfo } from "../../shared/types/UserInfo";
import { WorldServerConn } from "../WorldServer";
import { TokenUtils } from "../../TokenUtils";
import { worldServer } from "../../WorldServerMain";

let defaultUserInfo: UserInfo = {
    uid: '',
    name: '',
    visualId: 0,
}

export async function ApiJoinSubWorld(call: ApiCall<ReqJoinSubWorld, ResJoinSubWorld>) {

    let req = call.req;
    let serverToken = TokenUtils.genWorldServerLoginToken(req.uid, worldServer.thisServerUrl, req.subWorldId, req.time);
    if (serverToken != req.token) {
        return call.error('AUTH_FAILED');
    }
    // Login
    const currentUser = await worldServer.getUserInfoFromMaster(req.uid) || defaultUserInfo;

    const conn = call.conn as WorldServerConn;
    conn.currentUser = currentUser;

    let subWorld = worldServer.id2SubWorld.get(req.subWorldId);
    if (!subWorld) {
        return call.error('子世界不存在', { code: 'SUB_WORLD_NOT_EXISTS' });
    }

    if (subWorld.userNum >= subWorld.maxUser) {
        return call.error('子世界已满员');
    }

    // 用户已经在本子世界中，可能是通过其它设备登录，踢出旧连接
    for(let i = subWorld.conns.length - 1; i >= 0; --i){
        let c = subWorld.conns[i];
        if(!c.currentUser || c.currentUser.uid === currentUser.uid){
            subWorld.conns.splice(i,1);
        }
    }

    // 用户正在其它子世界中，从之前的子世界中退出
    if (conn.currentSubWorld && subWorld) {
        conn.currentSubWorld.onRPC_Leave(conn);
    }

    subWorld.onRPC_Enter(conn);

    subWorld.conns.push(conn);
    conn.currentSubWorld = subWorld;
    subWorld.listenMsgs(conn);
    subWorld.lastEmptyTime = undefined;
    subWorld.lastUpdateTime = Date.now();

    worldServer.userId2Conn[currentUser.uid] = conn;

    call.succ({
        currentUser: currentUser
    });
}